package com.gao.controller;

import com.gao.domain.User;
import com.gao.util.LoginCacheUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

/**
 * @author 高鹏
 * @time 2020/04/06 12:12:55
 */
@Controller
@RequestMapping("view")
public class ViewController {
    @RequestMapping("login")
    public String toLogin(@RequestParam(required = false, defaultValue = "") String from, HttpSession session,
                          @CookieValue(value = "token", required = false) Cookie cookie) {
        if(StringUtils.isEmpty(from)) {
            from = "http://www.codeshop.com:9010";
        }
        // 为了简单，这里省略校验url格式的逻辑
        session.setAttribute("from", from);

        if(cookie != null) {
            // 如果是已经登录的用户再次访问登录系统时，就直接重定向
            String token = cookie.getValue();
            User user = LoginCacheUtils.loginUser.get(token);
            if (user != null) {
                return "redirect:" + from;
            }
        }

        return "login";
    }
}
